package com.laboratory.serviceprovide.setting.service.impl;

import com.Laboratory.setting.service._projectService;
import com.Laboratory.utilPojo.emailMessage;
import com.Laboratory.utilPojo.projectWithStateAndTime;
import com.Laboratory.utilPojo.projectWithUrl;
import com.Laboratory.workBench.pojo.project;
import com.Laboratory.workBench.pojo.room;
import com.Laboratory.workBench.pojo.teacher;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.laboratory.serviceprovide.constant.constantArgs;
import com.laboratory.serviceprovide.util.emailUtil;
import com.laboratory.serviceprovide.util.fileUtil;
import com.laboratory.serviceprovide.workBench.mapper.projectMapper;
import com.laboratory.serviceprovide.workBench.mapper.roomMapper;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @Author acok
 * @description:TODO
 * @Date 2023/1/4 16:15
 * @Version 1.0
 */
@DubboService(interfaceClass = _projectService.class,version = "1.0.0",timeout = 5000)
public class _projectServiceImpl implements _projectService {
    @Resource
    private projectMapper projectMapper;
    @Resource
    private roomMapper roomMapper;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public List<projectWithStateAndTime> getProjectListByCondition(Map<String, Object> map) {
        return projectMapper.getProjectListByCondition(map);
    }

    @Override
    public int getProjectListRowsByCondition(Map<String, Object> map) {
        return projectMapper.getProjectListRowsByCondition(map);
    }

    @Override
    public int updateProjectState(projectWithStateAndTime project,String fromAccount,String passwordCode) {
        int result=projectMapper.updateProjectState(project);
        if(result>0){
            emailMessage e=new emailMessage();
            e.setFromAccount(fromAccount);
            e.setFromPassword(passwordCode);
            e.setAddressAccount(project.getCode());
            e.setEmailTitle(constantArgs.EMAIL_TITLE);
            if("1".equals(project.getProjectstate())){
                //随机查询可预约教室进行分配添加至邮件
                room room = roomMapper.getRoomByRandom();
                //更新教室状态
                roomMapper.updateRoomStateById(room.getId());
                //新建项目-固定教室关系记录
                projectMapper.createProjectRoomRecord(  UUID.randomUUID().toString().replace("-",""),
                                                        project.getId(),
                                                        room.getId());
                e.setEmailContent("["+
                        project.getProjectname()+"]"+
                        constantArgs.EMAIL_SUCCESS_CONTENT+"——指导教师:"+
                                project.getTeacherid()+"——固定教室:"+room.getRoomno()+"(位置:"+room.getRoomlocation()+")");
            }else {
                e.setEmailContent(
                        "["+project.getProjectname()+"]"+
                        constantArgs.EMAIL_FAIL_CONTENT+",请仔细阅读注意事项后重新申请!");
            }
            try {
                emailUtil.sendEmail(e);
            }catch (Exception exception){
                exception.printStackTrace();
            }
        }
        return result;
    }

    @Override
    public int clearProjectMessageById(String id) {
        int i = projectMapper.deleteProjectStateById(id);
        int j = projectMapper.deleteProjectById(id);
        List<String> fileNames = projectMapper.getFileNameByProjectId(id);
        int files = fileUtil.deleteFileByProjectId(fileNames);
        int k=0;
        if (files==2) {
            k = projectMapper.deleteProjectFileById(id);
        }
        return i+j+k;
    }

    @Override
    public int clearOverTimeProjectRecord(String id) {
        int i = projectMapper.deleteProjectStateById(id);
        int j = projectMapper.deleteProjectById(id);
        List<String> fileNames = projectMapper.getFileNameByProjectId(id);
        int files = fileUtil.deleteFileByProjectId(fileNames);
        int k=0;
        if (files==2) {
            k = projectMapper.deleteProjectFileById(id);
        }
        if(j>0){
            roomMapper.updateRoomStateByIdForClearProject(id);
            projectMapper.deleteProjectRoomRelation(id);
        }
        return i+j+k;
    }

    @Override
    public List<project> selectOverTimeProjectRecord() {
        return projectMapper.selectOverTimeProjectRecord();
    }

    @Override
    public List<project> selectInvalidProjectApply() {
        return projectMapper.selectInvalidProjectApply();
    }

    @Override
    public List<projectWithUrl> getProjectFileList() {
        ValueOperations<String, String> ops= stringRedisTemplate.opsForValue();
        List <projectWithUrl> resultList=null;
        if(ops.get(constantArgs.REDIS_PROJECT_FAIL_LIST_KEY)==null){
            resultList= projectMapper.getProjectFileList();
            System.out.println(resultList.get(1).toString());
            if(resultList.size()>0){
                ops.set(constantArgs.REDIS_PROJECT_FAIL_LIST_KEY, JSON.toJSONString(resultList),60*60*6, TimeUnit.SECONDS);
            }
        }else {
            resultList = JSON.parseObject(ops.get(constantArgs.REDIS_PROJECT_FAIL_LIST_KEY), new TypeReference<List<projectWithUrl>>() {});
        }
        return resultList;
    }

    @Override
    public int deleteTeacherById(String teacherId) {
        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
        int i = projectMapper.deleteTeacherById(teacherId);
        if(i>0){
            if(ops.get(constantArgs.REDIS_TEACHER_LIST_KEY)!=null){
                List<teacher> teachers = JSON.parseObject(ops.get(constantArgs.REDIS_TEACHER_LIST_KEY), new TypeReference<List<teacher>>() {
                });
                assert teachers != null;
                int len=teachers.size();
                for (int k=0;k<len;k++){
                    if(teachers.get(k).getId().equals(teacherId)){
                        /*移除指定元素*/
                        teachers.remove(k);
                        /*移除后集合长度变化*/
                        len--;
                        /*循环指针定位到移除元素（k-1）位置
                        保证新集合k位置（被移除元素后一位元素填补）元素被检测到*/
                        k--;
                    }
                }
                ops.set(constantArgs.REDIS_TEACHER_LIST_KEY,JSON.toJSONString(teachers),30*60,TimeUnit.SECONDS);
            }
        }
        return i;
    }

    @Override
    public int createTeacher(teacher teacher) {
        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
        int i = projectMapper.createTeacher(teacher);
        if (i>0){
            if (ops.get(constantArgs.REDIS_TEACHER_LIST_KEY)!=null){
                List<teacher> teachers = JSON.parseObject(ops.get(constantArgs.REDIS_TEACHER_LIST_KEY), new TypeReference<List<teacher>>() {
                });
                assert teachers != null;
                teachers.add(teacher);
                ops.setIfPresent(constantArgs.REDIS_TEACHER_LIST_KEY,JSON.toJSONString(teachers),30*60,TimeUnit.SECONDS);
            }
        }
        return i;
    }
}
